from __future__ import annotations

from decimal import Decimal
from typing import Optional, List, Dict

from pydantic import BaseModel, ConfigDict, Field


class GoodsSkuBo(BaseModel):
    goods_sku_id: str = Field(..., description="SKU唯一标识")
    goods_sku_no: Optional[str] = Field(None, max_length=50)
    image_id: Optional[int] = Field(None, ge=0)
    goods_price: Decimal = Field(..., decimal_places=2, ge=0)
    line_price: Decimal = Field(..., decimal_places=2, ge=0)
    stock_num: int = Field(0, ge=0)
    goods_weight: Decimal = Field(Decimal("0"), decimal_places=4, ge=0)
    goods_props: Optional[Dict[str, str]] = None
    spec_value_ids: Optional[str] = Field(None, max_length=200)

    # 把逗号字符串自动拆成 List[int]，方便前端
    @property
    def spec_id_list(self) -> List[int]:
        if not self.spec_value_ids:
            return []
        return [int(i) for i in self.spec_value_ids.split(",") if i.isdigit()]

    # 入库前再把 list 拼回字符串（可选）
    def set_spec_ids(self, ids: List[int]) -> None:
        self.spec_value_ids = ",".join(map(str, ids))


class GoodsSkuVo(BaseModel):
    id: int
    goods_id: int
    sku_id: str = ""
    sku_no: Optional[str] = None
    image_id: Optional[int] = None
    goods_price: Decimal
    line_price: Decimal
    stock_num: int
    goods_weight: Decimal = Decimal("0")
    goods_props: Optional[dict] = None
    spec_value_ids: Optional[str] = None
    image_url: Optional[str] = None
    image: Optional[str] = None

    model_config = ConfigDict(from_attributes=True,
                              json_encoders={Decimal: float})


class SkuSaleAttributeValueBo(BaseModel):
    id: int
    attr_id: int
    attr_name: str
    attr_value: str
    attr_sort: int
